<template>
  <el-form
    class="form-container"
    ref="child"
    label-width="100px"
    :model="formModel"
    :rules="rules"
  >
    <h3>当前子组件提供对外父组件的统一校验方法和数据收集方法</h3>
    <el-form-item label="部门" prop="dept">
      <el-select v-model="formModel.dept" clearable>
        <el-option :value="1" label="行政部"></el-option>
        <el-option :value="2" label="财务部"> </el-option>
        <el-option :value="3" label="销售部"></el-option>
        <el-option :value="4" label="服务部"> </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="手机号" prop="phone">
      <el-input v-model="formModel.phone"></el-input>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  name: 'child',
  data () {
    return {
      rules: {
        dept: [
          { required: true, message: '请选择部门', trigger: ['change', 'blur'] }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: ['change', 'blur'] },
          { max: 11, message: '手机号最多11位', trigger: ['change', 'blur'] }
        ]
      },
      formModel: {
        dept: '',
        phone: ''
      }
    }
  },
  methods: {
    /**
     * 假设当前组件为子组件， 一个抽象组件， 提供统一的对【父组件】接口
     *
     * 父组件通过 this.$refs['child'].checkFields()  调用
     *
     * @returns Promise 对象
     */
    checkFields () {
      return new Promise(async (resolve, reject) => {
        try {
          const res = await this.$refs['child'].validate()

          resolve(res)
        } catch (e) {
          reject(e)
        }
      })
    },
    /**
     * 提供给父组件通过 $refs['child'].getFormModel() 调用
     */
    async getFormModel () {
      try {
        const isValid = await this.checkFields()

        console.log('isValid', isValid)
      } catch (e) {
        return null
      }

      return { ...this.formModel }
    }
  }
}
</script>

<style lang="less" scoped>
.form-container {
  /deep/ .el-form-item .el-form-item__label {
    color: #000;
  }
}
</style>
